(function ($) {
    var SUBJ_ANSWER_TYPE = {
        ATTACH: 1, CAMERA: 2, HAND_DRAW: 4, UPLOAD_FILE: 8
    }
    const SUBJ_ANSWER_UPDATE_TYPE = {
        image: true, other: true,
    }
    try {
        document.documentElement.focus();
    } catch (e) {
    }/*hack for ie9*/
    PAPER_CLASS = {
        QUESTION: ".ui-question",
        QUESTION_GROUP: ".ui-question-group",
        GROUP_TITLE: ".ui-question-group-title",
        QUESTION_SERIAL_NO: ".ui-question-serial-no",
        QUESTION_INDEPENDENCY: '.ui-question-independency',
        QUESTION_SUB: '.ui-question-sub',
    };
    $.ajaxSetup({cache: false});
    window.__RTE = null;
    window.currentQuestion = null;
    var recNum = 0, isRichText = true, questionArray = [], currentQuestionIndex = -1;
    $(window).bind("contextmenu", function () {
        return false;
    });
    $(window).bind("selectstart", function () {
        return false;
    });

    function FindApi(p) {
        recNum++;
        if (!!p.__ExamIns) {
            return p.__ExamIns;
        } else if (recNum < 6) {
            if (!!p.parent) {
                return FindApi(p.parent);
            }
        }
        return null;
    };window.__Exam_PaperInit = function () {
        var uiOverflow = $('.ui-overflow'), win = $(window), paperQuestion = {};
        //uiOverflow.show();
        uiOverflow.width(win.width());
        uiOverflow.height(win.height());
        //uiOverflow.html('<p>正在加载题目...</p>');
        window.__RTE = FindApi(window);
        var exam = window.__RTE;
        if (!exam) {
            uiOverflow.show();
            uiOverflow.html('<p>考试初始化失败，请刷新试卷，或退出重新考试..</p>');
        } else {
            if (exam.isConfuseOrder()) {
                confuseOrderFunc(exam.getUserExamId());  /*0.5为混淆因子*/
            }
            try {
                showAudioPlayers();
            } catch (e) {
            }
            if (exam.isEnterExam()) {  /*是考试*/
                _initQuestionGroups(exam);
                //下一题，下一题的功能，按左键或是右键
                $(document).keydown(function (event) {
                    if (event.keyCode == 37) {
                        __offsetQuestion(-1);
                    } else if (event.keyCode == 39) {
                        __offsetQuestion(1);
                    }
                });

                $('.ui-question-options>li .ui-question-options-order').on('click', function () {  /*选择题选项处理*/
                    var t = $(this).parent(), parent = t.parent().parent(), answer = '', isChanged = false;
                    while (!!parent) {
                        if (parent.hasClass('ui-question')) {
                            break;
                        } else {
                            parent = parent.parent();
                        }
                    }
                    if (!!parent) {
                        if (parent.hasClass('undone')) {
                            parent.removeClass('undone');
                        }
                        if (parent.hasClass('ui-question-1')) {/*单选题*/
                            if (!t.hasClass('ui-option-selected')) {
                                $('.ui-question-options>li.ui-option-selected', parent).removeClass('ui-option-selected');
                                t.addClass('ui-option-selected');
                                answer = t.attr('code');
                                isChanged = true;
                            }
                        } else if (parent.hasClass('ui-question-2')) {/*多选题*/
                            isChanged = true;
                            t.toggleClass('ui-option-selected');
                            $('.ui-question-options>li.ui-option-selected', parent).each(function () {
                                answer = answer + $(this).attr('code');
                            });
                        }
                        if (isChanged) {
                            exam.SaveItem(parent.prop('id').substring(2), parent.attr('code').substring(4), answer, '');
                        }
                    }
                });
                /* 富文件的保存答案的功能 */
                /* 答题的时候显示富文本的代码 */

                /* 附件上传后会激活textarea的onchange事件，富文本也需要上传附件的功能 */
                $('.ui-question-textarea').on('input propertychange focus change', function () {
                    var t = $(this), parent = t.parent();
                    if (!!parent) {
                        var answer = t.val();
                        setTimeout(function () {
                            _saveItem._preSaveTextAreaItem(parent, answer);
                        }, 200);
                    }
                });
            }
            $('img').each(function () {
                var img = $(this), imgW = img.attr('width'), imgH = img.attr('height');
                if (imgW) {
                    img.css('width', imgW + 'px');
                }
                if (imgH) {
                    img.css('height', imgH + 'px');
                }
            });
            //去掉css的样式，有的选项把正确答案的样式也加上了。
            $('.ui-question-options>li').each(function () {
                var li = $(this);
                $('p,div,span', li).each(function () {
                    $(this).attr('style', '');
                })
            });
            exam.Init(window);
        }
    };

    function _initQuestionGroups(exam) {
        /**
         *得到所有大题的title和小题的id，同时隐藏大题，大题说明，和小题
         */
        var questionGroups = {}, groups = [], questions = [],groupsRemark=[];
        $(PAPER_CLASS.QUESTION_GROUP).each(function (index) {
            var t = $(this), subQues = [], groupTitle = $(PAPER_CLASS.GROUP_TITLE, t);
            var textgroupTitle = $(".text-group", t).text();
            var titleRemarkJson={"textgroupTitle":textgroupTitle};
		    titleRemarkJson.groupTitleRemark=$('.text-group-description', t).text();
			groupsRemark[index]=titleRemarkJson;
            groups[index] = groupTitle.text();
            if (t.hasClass('question-group-4')) {
                $(PAPER_CLASS.QUESTION_SUB, t).each(function () {
                    var tt = $(this), quesId = tt.attr('id');
                    var number = $(PAPER_CLASS.QUESTION_SERIAL_NO, tt).text();
                    subQues.push({number: number, id: quesId});
                    questionArray.push(quesId);
                });
            } else {
                $(PAPER_CLASS.QUESTION, t).each(function () {
                    var tt = $(this), quesId = tt.attr('id');
                    var number = $(PAPER_CLASS.QUESTION_SERIAL_NO, tt).text();
                    subQues.push({number: number, id: quesId});
                    questionArray.push(quesId);
                });
            }
            questions[index] = subQues;
        });
        questionGroups.groups = groups;
        questionGroups.questions = questions;
 		questionGroups.groupsRemark = groupsRemark;
        exam.setQuestionGroups(questionGroups);
    }

    function confuseOrderFunc(seed) {
        //自定义随机数，如果种子相同，随机数序列也是相同的
        var random = new Random(seed);
        $('.ui-question-group').each(function () {  /*对所有大题遍历*/
            var qn = $('.ui-question-independency', this).length;  /*大题下的题目数*/
            var confOrderNum = parseInt(qn * 0.8);  /*混淆次数*/
            for (var i = 0; i < confOrderNum; i++) {
                var rad1 = random.rand(qn);
                var rad2 = random.rand(qn);

                if (rad2 == rad1) {
                    if (rad2 == 0) rad2 = qn - 1; else rad2 = rad1 - 1;
                }
                var que1 = $('.ui-question-independency:eq(' + rad1 + ')', this);
                var que2 = $('.ui-question-independency:eq(' + rad2 + ')', this);
                var html1 = que1.html();
                var queId1 = que1.attr("id");
                var code1 = que1.attr("code");
                var order1 = $('.ui-question-serial-no:first', que1).text();
                var order2 = $('.ui-question-serial-no:first', que2).text();
                que1.html(que2.html());
                que1.attr("id", que2.attr("id"));  /*id变*/
                que1.attr("code", que2.attr("code"));  /*code变*/
                $('.ui-question-serial-no:first', que1).text(order1); /*order值不变*/
                que2.html(html1);
                que2.attr("id", queId1);
                que2.attr("code", code1);
                $('.ui-question-serial-no:first', que2).text(order2);
            }

        });
    };

    function confuseChoiceFunc(confuseChoiceIndex) {
        $('.ui-question .ui-question-options').each(function () { /*遍历有选项的题目*/
            var cn = $('li', this).length;  /*选项数*/
            var confChoiceNum = parseInt(cn * confuseChoiceIndex);  /*混淆次数*/
            for (var i = 0; i < confChoiceNum; i++) {
                var rad1 = parseInt(Math.random() * cn);
                var rad2 = parseInt(Math.random() * cn);
                if (rad2 == rad1) {
                    if (rad2 == 0) rad2 = cn - 1; else rad2 = rad1 - 1;
                }
                var choice1 = $('li:eq(' + rad1 + ')', this);
                var choice2 = $('li:eq(' + rad2 + ')', this);
                var code1 = choice1.attr('code');
                var code2 = choice2.attr('code');
                var order1 = $('.ui-question-options-order', choice1).text();
                var order2 = $('.ui-question-options-order', choice2).text();
                var html1 = choice1.html();
                choice1.html(choice2.html());
                choice1.attr('code', code2); /*code值交换*/
                $('.ui-question-options-order', choice1).text(order1); /*order值不变*/
                choice2.html(html1);
                choice2.attr('code', code1);
                $('.ui-question-options-order', choice2).text(order2);
            }
        });
    };
    /*用户的答案初始化试卷*/
    window.__OnInited = function (answers, answerType) {
        window.__RTE = FindApi(window);
        var exam = window.__RTE, length, keys = [], txtAnswerObj = {};
        // 初使化问答题的样式，交白卷和没答案的样式
        if (!exam.isEnterExam()) {
            $('.ui-question-3').each(function () {
                var t = $(this);
                $('.ui-question-textarea', t).hide();
                var userAnswer = $('<div class="ui-user-answer"></div>');
                userAnswer.append('<label>考生回答：</label>');
                var userAnswerAI = $('<div class="ui-user-answer-ai" style="width: 100%;margin-top: 5px"></div>');
                $('.ui-question-title', t).after(userAnswerAI);
                $('.ui-question-title', t).after(userAnswer);
            });
        }
        if (!!answers && $.isArray(answers) && answers != "") {
            length = answers.length;
            for (var i = 0; i < length; i++) {
                var answer = answers[i], qid = 'q_' + answer.id, question = $('#' + qid);
                if (question.hasClass('ui-question-3')) {
                    if (!exam.isEnterExam()) {
                        $('.ui-question-textarea', question).hide();
                    }
                    keys.push(qid);
                    txtAnswerObj[qid] = answer.file;
                }
                initUserAnswer(answer, exam.isEnterExam());
            }
        }

        if (exam.isEnterExam()) {
            //appendUplodWidget(txtAnswerObj);
            _upload.init();
            _upload.showAttachFiles(txtAnswerObj, true);
        } else {
            //_upload.showAttachFiles(txtAnswerObj, false);
            showAnswerAttaches(keys, txtAnswerObj);
            //_upload.showMutiAttach(keys, txtAnswerObj);
        }

        //上一题和下一题的功能
        if (exam.isEnterExam()) {
            initTextareaEditor(answerType);
            _setAllQuestionsHide();
            __offsetQuestion(1);
        }
        //$('.ui-overflow').hide();
    };

    function _setAllQuestionsHide() {
        var paper = window.document;
        $(PAPER_CLASS.GROUP_TITLE, paper).hide();
        $(PAPER_CLASS.QUESTION, paper).hide();
        $(PAPER_CLASS.QUESTION_GROUP, paper).hide();
    };

    var _saveItem = {
        lastAnswerHash: null, _preSaveTextAreaItem: function (parent, answer) {
            var exam = window.__RTE;
            if (!exam.isEnterExam()) {
                return false;
            }
            if (parent.hasClass('undone')) {
                parent.removeClass('undone');
            }
            var ul = $('ul.ui-file-list-new', parent), values = $('li input[name="filePath"]', ul), val = '';
            for (var i = 0; i < values.length; i++) {
                if (!!val) {
                    val = val + ",";
                }
                val = val + $(values[i]).val();
            }
            var currentAnswerHash = parent.prop('id').substring(2) + "__" + answer + '___' + val;
            if (_saveItem.lastAnswerHash == currentAnswerHash) {
                return;
            } else {
                exam.SaveItem(parent.prop('id').substring(2), parent.attr('code').substring(4), answer, val);
                _saveItem.lastAnswerHash = currentAnswerHash;
            }

        }
    }

    function initTextareaEditor(answerType) {
        window.__RTE = FindApi(window);
        var exam = window.__RTE;
        if (!exam.isEnterExam()) {
            return false;
        }
        var lastRichSaveTime = (new Date()).getTime();
        $('.ui-question-textarea').each(function () {
            var t = $(this), parent = t.parent();
            if (!!parent) {
                var id = parent.attr('id') + "_textarea";
                t.attr('id', id);
                /*'kindEditor'*/
                var editor = KindEditor.create('#' + t.attr('id'), {
                    cssData: 'body {font-size: 16px}',
                    items: [],
                    pasteType: 0,
                    width: '95%',
                    resizeType: 0,
                    afterBlur: function () {
                        KindEditor.sync('#' + t.attr('id'));
                        var answer = KindEditor('#' + t.attr('id')).val();
                        _saveItem._preSaveTextAreaItem(parent, answer);
                    },
                    afterChange: function () {
                        var currTime = (new Date()).getTime();
                        if ((currTime - lastRichSaveTime) < 10 * 1000) {
                            return;
                        } else {
                            lastRichSaveTime = currTime;
                        }
                        KindEditor.sync('#' + t.attr('id'));
                        var answer = KindEditor('#' + t.attr('id')).val();
                        _saveItem._preSaveTextAreaItem(parent, answer);
                    }
                });
                var questionId = t.parent().attr('id');
                /**
                 * 增加主观题的其它答题方式
                 */
                var toolsBar = $('<div class="ui-textarea-toolsbar"></div>');
                $('.ui-question-title', parent).after(toolsBar);
                const image = (answerType & SUBJ_ANSWER_TYPE.ATTACH) === SUBJ_ANSWER_TYPE.ATTACH;
                const other = (answerType & SUBJ_ANSWER_TYPE.UPLOAD_FILE) === SUBJ_ANSWER_TYPE.UPLOAD_FILE;
                if ((answerType & SUBJ_ANSWER_TYPE.ATTACH) === SUBJ_ANSWER_TYPE.ATTACH) {
                    SUBJ_ANSWER_UPDATE_TYPE.image = image;
                    SUBJ_ANSWER_UPDATE_TYPE.other = other;
                    const button = $('<button>' + (other ? "上传附件" : "上传图片") + '</button>').data('qid', questionId);
                    button.on('click', function () {
                        handleClickAttach($(this).data('qid'));
                    });
                    toolsBar.append(button)
                }

                if ((answerType & SUBJ_ANSWER_TYPE.CAMERA) === SUBJ_ANSWER_TYPE.CAMERA) {
                    var cameraBtn = $('<button>拍照</button>').data('tid', questionId);
                    cameraBtn.on('click', function () {
                        handleClickTakePicture(editor);
                    })
                    toolsBar.append(cameraBtn)
                }
                if ((answerType & SUBJ_ANSWER_TYPE.HAND_DRAW) === SUBJ_ANSWER_TYPE.HAND_DRAW) {
                    var drawBtn = $('<button>手写</button>').data('tid', questionId);
                    drawBtn.on('click', function () {
                        var tid = $(this).data('tid'), questionId = tid.replace("q_", "");
                        _currentEditor = editor;
                        //handleClickDrawPainter(editor, questionId, tid);
                        handleClickHandDraw(editor, questionId, tid);
                    })
                    toolsBar.append(drawBtn)
                }
            }
        })
    }

    /*======================= 查看答卷的时候，显示附件=========================== */

    function showAnswerAttaches(keys, txtAnswerObj) {
        if (!!keys && $.isArray(keys)) {
            for (var i = 0; i < keys.length; i++) {
                var qid = keys[i], question = $('#' + qid), value = txtAnswerObj[qid];
                if (!!value) {
                    var content = $('<div class="ui-question-attach"></div>');
                    var values = value.split(','), length = values.length;
                    for (var it = 0; it < length; it++) {
                        var val = values[it], tmps = val.split('/');
                        if(val.indexOf("https")>-1){
                        	var fname = tmps[tmps.length-1];
                        	content.append(_upload._createImageElement(qid.substr(2),val, fname));
                        }else{
	                        if (tmps.length > 0) {
	                            var __id = tmps[0], __name = (tmps.length > 1 ? tmps[1] : tmps[0]);
	                            content.append(_upload._createImageElement(qid.substr(2), __id, __name));
	                        }
                        }
                    }
                    $('.ui-user-answer', question).append(content);
                }
            }
        }
    }

    /* ==================== 设置题目答案=================== */
    function initUserAnswer(answer, isExam) {
        var qid = 'q_' + answer.id, question = $('#' + qid);
        if (question && question.length > 0) {
            if (question.hasClass('ui-question-1')) { /*单选题*/
                $('.ui-question-options>li[code="' + answer.answer + '"]', question).addClass('ui-option-selected');
            } else if (question.hasClass('ui-question-2')) {  /*多选题*/
                $('.ui-question-options>li', question).each(function () {
                    var t = $(this);
                    if (answer.answer.indexOf(t.attr('code')) != -1) {
                        t.addClass('ui-option-selected');
                    }
                });
            } else if (question.hasClass('ui-question-3')) {   /*问答题*/
                if (isExam) {
                    $('.ui-question-textarea', question).val(answer.answer);
                } else {
                    //查看答卷AI提示
                    if (answer.hasAi) {
                        if (parseInt(answer.aiScore) >= 0) {
                            $('.ui-user-answer-ai', question)[0].innerHTML = "<span style='color: #3FC474'>该题为AI自动判分，请以参考答案为准</span>";
                        } else {
                            $('.ui-user-answer-ai', question)[0].innerHTML = "<span style='color: red'>该题AI自动判分失败，请以参考答案为准。</span>";
                        }
                    }
                    $('.ui-user-answer', question).append(answer.answer);
                    $('.ui-question-textarea', question).val(answer.answer);
                    if (!answer.twoScore && !answer.twoScore) {
                        $('.ui-question-user-score', question).prepend('<lable style="color: #ea7726;" >'+clearNull(answer.oneScore)+'</lable>');
                    }
                    if (!answer.finalScore && answer.twoScore && answer.twoScore != "") {
                        $('.ui-question-user-score', question).prepend('<lable>一评：</lable><lable style="color: #ea7726;" >' + clearNull(answer.oneScore) + '</lable>&nbsp;|&nbsp;<lable>二评：</lable><lable style="color: #ea7726;" >' + clearNull(answer.twoScore) + '</lable>&nbsp;|&nbsp;');
                    }
                    if (answer.finalScore && answer.finalScore != "") {
                        $('.ui-question-user-score', question).prepend('<lable>一评：</lable><lable style="color: #ea7726;" >' + clearNull(answer.oneScore) + '</lable>&nbsp;|&nbsp;<lable>二评：</lable><lable style="color: #ea7726;" >' + clearNull(answer.twoScore) + '</lable>&nbsp;|&nbsp;<lable>仲裁：</lable><lable style="color: #ea7726;" >' + clearNull(answer.finalScore) + '</lable>');
                    }
                }
            }
            if (!!answer.finalCheckMemo) {
                question.after('<div class="ui-question-checkMemo"><label style="color: #ea7726;">终评评语：</label>' + clearNull(answer.finalCheckMemo) + '</div>');
            }
            if (!!answer.twoCheckMemo) {
                question.after('<div class="ui-question-checkMemo"><label style="color: #ea7726;">二评评语：</label>' + clearNull(answer.twoCheckMemo) + '</div>');
            }
            if (!!answer.checkMemo) {
                if (answer.finalCheckMemo == null && answer.twoCheckMemo == null) {
                    question.after('<div class="ui-question-checkMemo"><label style="color: #ea7726;">评语：</label>' + clearNull(answer.checkMemo) + '</div>');
                } else {
                    question.after('<div class="ui-question-checkMemo"><label style="color: #ea7726;">一评评语：</label>' + clearNull(answer.checkMemo) + '</div>');
                }
            }
        }
    };
    
    function clearNull(arg1){ 
		if(arg1 == null){
			return "";
		}
		if(arg1 == 'null'){
			return "";
		}
		if(arg1 == undefined){
			return "";
		}
		if(arg1 == 'undefined'){
			return "";
		}
		return arg1;
	} 
	
    /* 显示标准答案和解析 */
    window.__ShowAnswerAndHint = function (answers) {
        if (!!answers && $.isArray(answers)) {
            len = answers.length;
            for (var i = 0; i < len; i++) {
                var answer = answers[i];
                showQuestionAnswerAndHint(answer);
            }
            //reTranslate(); /*重新显示公式符号*/
        }
    };
    /* 在音视频的链接 加上mouse event */
    window.__InitLinks = function () {
        var videoBox = $('.exam-video-box'), player = $('#exam-video-player'), videoNode, audioNode,
            loading = $('<div style="color:white;padding:5px;">正在下载媒体文件，请稍后...</div>');
        if (videoBox.length == 0) {
            var videoBox = $('<div class="exam-video-box"><span>X</span></div>').append(loading);
            var videoNode = $('<video id="exam-video-player" width="600" height="300" controls="controls" controlsList="nodownload" autoplay="autoplay"></video>');
            var audioNode = $('<audio id="exam-audio-player" width="600" height="54" style="width:600px" controls="controls" controlsList="nodownload" autoplay="autoplay"></audio>');
            videoBox.append(videoNode.hide()).append(audioNode.hide());
            $(document.body).append(videoBox.hide());
            videoNode.bind('contextmenu', function () {
                return false;
            });
            audioNode.bind('contextmenu', function () {
                return false;
            });
        }

        function addClickEvent(thisTag, extName, href) {
            thisTag.attr("data-url", href).attr('href', 'javascript:void(0)').removeAttr("target");
            if (extName == '.mp4') {
                thisTag.addClass('ui-video-link');
            } else {
                thisTag.addClass('ui-audio-link');
            }
            thisTag.on('click', function () {
                videoBox.show();
                loading.show();
                var url = thisTag.attr('data-url');
                if (extName == '.mp4') {
                    audioNode.hide();
                    videoBox.removeClass('exam-audio-box');
                    player = videoNode;
                } else {
                    videoBox.addClass('exam-audio-box');
                    videoNode.hide();
                    player = audioNode;
                }
                player.attr('src', url);
                player.on('loadedmetadata', function () {
                    loading.hide();
                    player.show();
                })
            })
        }

        $('a').each(function () {
            var t = $(this), href = $(this).attr('href');
            if (href) {
                var myhref = href.toLowerCase();
                if (myhref.length - 4 > 0) {
                    var extName = myhref.substring(myhref.length - 4);
                    if (extName == '.mp4' || extName == '.mp3' || extName == '.mpa') {
                        addClickEvent(t, extName, href);
                    }
                }
            }
        });
        $('span', videoBox).on('click', function () {
            videoBox.hide();
            videoNode.attr('src', '').hide();
            audioNode.attr('src', '').hide();
        })
    }

    function showQuestionAnswerAndHint(answer) {
        var question = $('#q_' + answer.questionId);
        if (question && question.length > 0) {
            if (question.hasClass('ui-question-1') || question.hasClass('ui-question-2')) {
                for (var j = 0; j < answer.answer.length; j++) {
                    var c = answer.answer.charAt(j);
                    $('.ui-question-options>li[code=' + c + ']', question).addClass('ui-correct-answer');
                }
            } else if (!question.hasClass('ui-question-4') && !!answer.answer) {  /*非复合题*/
                question.append('<div class="ui-question-answer"><label>参考答案：</label>' + answer.answer + '</div>');
            }
            // if (!!answer.hint) {
            //     question.append('<div class="ui-question-hint"><label>答案解析：</label>' + answer.hint + '</div>');
            // }
        }
    };
    /*老师批阅试卷的接口，显示分数和批注*/
    window.__rejectCheckUI = function (scores, basePath) {
        var exam = window.__RTE;
        if (!exam.isEnterExam()) {
            $('.ui-question-3').each(function () {
                var t = $(this), questionId = t.attr('id').substring(2);
                var fullScore = parseFloat($('.ui-question-score', t).text());
                var usd = $('<div class="ui-question-user-score">' + '<div class="score">' + '<label>得分：</label>' + '<input name="score" type="text" id="score_' + questionId + '" size="2" />(满分' + fullScore + '分)</div>' + '<div><button>1</button></div>' + '</div>');
                usd.append('<div class="showInfo" style="width: 100%;margin-top: 5px" id="showInfo_' + questionId + '"></div>');
                usd.append('<div class="remark"><label>评语1：</label><input type="text" id="remark_' + questionId + '" size="50"/><div>');
                $('.ui-question-answer', t).before(usd);
                $('#score_' + questionId, usd).on('change propertychange', function () {
                    var si = $(this), siId = si.attr('id').substring(6),
                        psqId = $('#q_' + questionId).attr('code').substring(4);
                    var thisFullScore = parseFloat($('.ui-question-score', $('#q_' + siId)).text());
                    if (si.hasClass('undone')) {
                        si.removeClass('undone');
                    }
                    exam.SaveCheckResult(siId, psqId, si.val(), thisFullScore);
                });
                $('#remark_' + questionId, usd).on('change propertychange', function () {
                    var remark = $(this), remarkId = remark.attr('id').substring(7),
                        psqId = $('#q_' + remarkId).attr('code').substring(4);
                    ;
                    if (remark.hasClass('undone')) {
                        remark.removeClass('undone');
                    }
                    exam.SaveCheckMemo(remarkId, psqId, remark.val());
                });
            });
        }
        if (!!scores && $.isArray(scores)) {
            var len = scores.length;
            for (var i = 0; i < len; i++) {
                var score = scores[i], question = $('#q_' + score.id);
                if (!!question) {
                    $('#score_' + score.id).val(score.score);
                    $('#remark_' + score.id).val(score.memo);
                    //是否AI阅卷提示
                    if (score.hasAi) {
                        if (parseInt(score.score)>= 0) {
                            document.getElementById('showInfo_' + score.id).innerHTML = "<span style='color: #3FC474'>该题为AI自动判分，如与参考答案存在偏差，请手动修改得分</span>";
                        } else {
                            document.getElementById('showInfo_' + score.id).innerHTML = "<span style='color: red'>该题AI自动判分失败，请人工打分。</span>";
                        }
                    }
                }
            }
        }
    };
    window.__checkNotChecked = function () {
        var count = 0;
        $('.ui-question-user-score input[name="score"]').each(function () {
            var t = $(this), score = t.val(), qid = t.attr('id').substring(6);
            var fullScore = parseFloat($('.ui-question-score', $('#q_' + qid)).text());
            ;
            if (score == '' || isNaN(score) || score > fullScore) {/* 没有正确批阅 */
                $('#q_' + qid).addClass('undone');
                count++;
            } else {
                $('#q_' + qid).removeClass('undone');
            }
        });
        return count;
    };

	function htmlEncodeByRegExp(str) {
		var s = '';
		if(str.length === 0) {
			return '';
		}
		s = str.replace(/&/g,'&amp;');
		s = s.replace(/</g,'&lt;');
		s = s.replace(/>/g,'&gt;');
		s = s.replace(/&lt;label&gt;参考答案：&lt;\/label&gt;/g,'');
		s = s.replace(/\'/g,'`');
		s= s.replace(/\"/g,'&quot;');
		return s;
	}
	
    function appendAnswerEmptyStatus(qt, questionId, allowAddLink) {
        if (allowAddLink) {
        // var str = htmlEncodeByRegExp(getQuestionStr(questionId));;
        //     qt.append('<span class="ui-question-answer-error">您没有作答&nbsp; <a class="ui-action-add" href="javascript:window.__RTE._addToUserErrorQuestions(\'' + questionId + '\',\'' + str + '\')">加入错题本</a></span>');
        // } else {
        // }
        qt.append('<span class="ui-question-answer-error">您没有作答</span>');
    };

    function appendAnswerErrorStatus(qt, questionId, allowAddLink) {
        // if (allowAddLink) {
        // var str = htmlEncodeByRegExp(getQuestionStr(questionId));;
        //     qt.append('<span class="ui-question-answer-error">您答错了 &nbsp; <a class="ui-action-add" href="javascript:window.__RTE._addToUserErrorQuestions(\'' + questionId + '\',\'' + str + '\')">加入错题本</a></span> ');
        // } else {
            
        // }
        qt.append('<span class="ui-question-answer-error">您答错了</span> ');

    };

    function appendAnswerRightStatus(qt) {
        // qt.append('<span class="ui-question-answer-right">您答对了</span>');
    };

    function appendErrorQuestAddLink(qt, questionId) {
    // var str = htmlEncodeByRegExp(getQuestionStr(questionId));;
    //     qt.append('<span><a class="ui-action-add" href="javascript:window.__RTE._addToUserErrorQuestions(\'' + questionId + '\',\'' + str + '\')">加入错题本</a></span>');
    };
    
    function getQuestionStr(questionId){
		var jsonStr = ""; //json 字符串
		var mark = "-mmarkk-"; //特殊分割标记
		var fhtMark = "-fhtMarkk-"; //特殊分割标记
		var  c = $("#q_"+questionId).attr("class").trim();
		var type = c.substr(c.length-1);
		
		//标题-mmarkk-题目类型-mmarkk-选项-ooptionn-选项-mmarkk-正确答案-mmarkk-解析
		//长度=4为 没有解析  长度=5为  有解析
		if(type == 1){
			jsonStr += $("#q_"+questionId).find(".ui-question-content-wrapper")[0].innerHTML;
			jsonStr +=mark;
			jsonStr += "1";
			jsonStr +=mark;
			var option = $("#q_"+questionId).find(".ui-question-options .ui-question-content-wrapper");
			for(var i=0;i<option.length;i++){
				if(i>0){
					jsonStr += "-ooptionn-"+option[i].innerHTML;
				}else{
					jsonStr += option[i].innerHTML;
				}
			}
			jsonStr +=mark;
			var answer = $("#q_"+questionId).find(".ui-question-options .ui-correct-answer").attr("code");
			jsonStr +=answer;
			var hint = $("#q_"+questionId).find(".ui-question-hint").text();
			jsonStr +=mark;
			jsonStr +=hint;
		}
		if(type == 2){
			jsonStr += $("#q_"+questionId).find(".ui-question-content-wrapper")[0].innerHTML;
			jsonStr +=mark;
			jsonStr += "2";
			jsonStr +=mark;
			var option = $("#q_"+questionId).find(".ui-question-options .ui-question-content-wrapper");
			for(var i=0;i<option.length;i++){
				if(i>0){
					jsonStr += "-ooptionn-"+option[i].innerHTML;
				}else{
					jsonStr += option[i].innerHTML;
				}
			}
			jsonStr +=mark;
			var answerList = $("#q_"+questionId).find(".ui-question-options .ui-correct-answer");
			for(var  i=0;i<answerList.length;i++){
				if(i>0){
					jsonStr += ","+$(answerList[i]).attr("code");
				}else{
					jsonStr += $(answerList[i]).attr("code");
				}
			}
			var hint = $("#q_"+questionId).find(".ui-question-hint").text();
			jsonStr +=mark;
			jsonStr +=hint;
		}
		if(type == 3){
			//标题-mmarkk-题目类型-mmarkk-参考答案-mmarkk-答案解析
			jsonStr += $("#q_"+questionId).find(".ui-question-content-wrapper")[0].innerHTML;
			jsonStr +=mark;
			jsonStr += "3";
			jsonStr +=mark;
			var answer = $("#q_"+questionId).find(".ui-question-answer").html();
			jsonStr +=answer;
			var hint = $("#q_"+questionId).find(".ui-question-hint").text();
			jsonStr +=mark;
			jsonStr +=hint;
		}
		if(type == 4){
			//标题-fhtMark-题目类型-fhtMark-答案解析-fhtMark-小提（包含123）
			jsonStr += $("#q_"+questionId).find(".ui-question-content-wrapper")[0].innerHTML;
			jsonStr +=fhtMark;
			jsonStr += "4";
			jsonStr +=fhtMark;
			jsonStr +=hint;
			var sub = $("#q_"+questionId).find(".ui-question-sub");
			for(var i =0;i<sub.length;i++){
				jsonStr += fhtMark;
				jsonStr += getQuestionStr(sub[i].id.substr(2));
			}
			var hint = $("#q_"+questionId).find(".ui-question-hint").text();
		}
		return jsonStr;
	}

    function appendCompositeAnswerErrorStatus(qt, parentId, allowAddLink) {
        qt.append('<span class="ui-question-answer-error">您答错了</span> ');
        if (allowAddLink) {
       		var parent = qt.parent().parent();
			var qid = parent.attr("id");	 
			addCompositeErrorQuestionLink(parent, qid.substr(2,qid.length));
        }
    };

    function appendCompositeAnswerEmptyStatus(qt, parentId, allowAddLink) {
        qt.append('<span class="ui-question-answer-error">您没有作答</span>');
        if (allowAddLink) {
            var parent = qt.parent().parent();
			var qid = parent.attr("id");
            addCompositeErrorQuestionLink(parent, qid.substr(2,qid.length));
        }
    };

    function addCompositeErrorQuestionLink(parent, parentId) {
        var title = $('.ui-question-title:first', parent);
        if (title.length > 0) {
            var add = title.find('.ui-action-add');
            if (add.length == 0) {
                appendErrorQuestAddLink(title, parentId);
            }
        }
    };

    /*显示答案是否正确的状态*/
    window.__ShowUserAnswerRightStatus = function (rightAnswers, allowAddLink) {
        if (!!rightAnswers && $.isArray(rightAnswers)) {
            var len = rightAnswers.length;
            for (var i = 0; i < len; i++) {
                var answer = rightAnswers[i];
                showUserAnswerRightStatus(answer, allowAddLink);
            }
        }
    };

    function showUserAnswerRightStatus(answer, allowAddLink) {
        var question = $('#q_' + answer.questionId), qt = $(".ui-question-title", question);
        if (question && question.length == 1) {
            if (answer.type == 1) {/*单选题*/
                var sel = $('.ui-question-options>li.ui-option-selected', question);
                if (!sel || sel.length == 0) {
                    if (question.hasClass('ui-question-independency')) {
                        appendAnswerEmptyStatus(qt, answer.questionId, allowAddLink);
                    } else {
                        appendCompositeAnswerEmptyStatus(qt, answer.parentId, allowAddLink);
                    }
                } else if (sel.attr("code") == answer.answer) {
                    appendAnswerRightStatus(qt);
                } else {
                    if (question.hasClass('ui-question-independency')) {
                        appendAnswerErrorStatus(qt, answer.questionId, allowAddLink);
                    } else {
                        appendCompositeAnswerErrorStatus(qt, answer.parentId, allowAddLink);
                    }
                }
            } else if (answer.type == 2) {
                var temp = answer.answer;
                var sel = $('.ui-question-options>li.ui-option-selected', question);
                if (!sel || sel.length == 0) {
                    if (question.hasClass('ui-question-independency')) {
                        appendAnswerEmptyStatus(qt, answer.questionId, allowAddLink);
                    } else {
                        appendCompositeAnswerEmptyStatus(qt, answer.parentId, allowAddLink);
                    }
                } else {
                    sel.each(function () {
                        var c = $(this).attr('code');
                        if (temp.indexOf(c) < 0) {
                            temp += c;
                            return;
                        } else {
                            temp = temp.replace(c, '');
                        }
                    });
                    if (temp.length == 0) {
                        appendAnswerRightStatus(qt);
                    } else {
                        if (question.hasClass('ui-question-independency')) {
                            appendAnswerErrorStatus(qt, answer.questionId, allowAddLink);
                        } else {
                            appendCompositeAnswerErrorStatus(qt, answer.parentId, allowAddLink);
                        }
                    }
                }
            } else if (answer.type == 3) {
                if (allowAddLink) {
                    if (question.hasClass('ui-question-independency')) {
                        appendErrorQuestAddLink(qt, answer.questionId);
                    } else {
	                    var parent = qt.parent().parent();
						var qid = parent.attr("id");	 
						addCompositeErrorQuestionLink(parent, qid.substr(2,qid.length));
                    }
                }
            }
        }
    };window.__ClientJudge = function (answers) {/*客户端判卷*/
        var score = 0, len, hash = {}, complexArr = [];
        if (!!answers && $.isArray(answers)) {
            len = answers.length;
            for (var i = 0; i < len; i++) {
                var answer = answers[i], question = $('#q_' + answer.questionId);
                if (question && question.length == 1) {
                    var tmpScore = 0;
                    if (answer.type == 1) {/*单选题*/
                        var sel = $('.ui-question-options>li.ui-option-selected', question);
                        if (sel && sel.attr('code')) {
                            if (answer.answer == sel.attr('code')) {
                                tmpScore = answer.score;
                            }
                        }
                    } else if (answer.type == 2) {/*多选题*/
                        var sel = $('.ui-question-options>li.ui-option-selected', question), tmpAnswer = answer.answer;
                        var len2 = sel.length;
                        var breaked = false;
                        for (var j = 0; j < len2; j++) {
                            var a = $(sel[j]);
                            if (tmpAnswer.indexOf(a.attr('code')) < 0) {
                                breaked = true;
                                break;
                            }
                            tmpAnswer = tmpAnswer.replace(a.attr('code'), '');
                        }
                        if (!breaked && tmpAnswer.length == 0) {
                            tmpScore = answer.score;
                        }
                    } else if (answer.type == 4) {/*复合题*/
                        var tmpId = 'a_' + answer.questionId;
                        if (!hash[tmpId]) {
                            hash[tmpId] = {subs: [], totalScore: 0};
                            complexArr.push(hash[tmpId]);
                        }
                        hash[tmpId].answer = answer;
                    }
                    if (answer.sub) {
                        var tmpId = 'a_' + answer.parentId;
                        if (!hash[tmpId]) {
                            hash[tmpId] = {subs: [], totalScore: 0};
                            complexArr.push(hash[tmpId]);
                        }
                        hash[tmpId].subs.push(tmpScore);
                        hash[tmpId].totalScore = hash[tmpId].totalScore + answer.score;
                    } else {
                        score = score + tmpScore;
                    }
                }
            }
            len = complexArr.length;
            for (var i = 0; i < len; i++) {
                var complex = complexArr[i], subs = complex.subs, totalScore = complex.answer.score, tmpScore = 0,
                    subLen = subs.length;
                for (var j = 0; j < subLen; j++) {
                    if (complex.totalScore > 0) {
                        tmpScore = tmpScore + (subs[j] / complex.totalScore) * totalScore;
                    }
                }
                score = tmpScore + score;
            }
        }
        return score;
    };

    function questionIsAnswered(t) {
        if (t.hasClass('ui-question-1') || t.hasClass('ui-question-2')) {
            if ($('li.ui-option-selected', t).length == 0) {
                return false;
            }
        } else if (t.hasClass('ui-question-3')) {
            var txt = $('.ui-question-textarea', t), c = txt.val();
            var hasFile = _upload.hasUploadFile(t);
            if ((!c || c.length == 0) && !hasFile) {
                return false
            }
        }
        return true;
    }

    window.__CheckUndone = function (qid) {
        var count = 0, firstId = null;
        if (!!qid) {
            if (!questionIsAnswered($('#' + qid))) {
                count++;
            }
        } else {
            $('.ui-question').each(function () {
                var t = $(this);
                if (!questionIsAnswered(t)) {
                    count++;
                    t.addClass('undone');
                }
            });
        }
        return {count: count, firstId: firstId};
    };
    window.__scrollToQuestion = function (qid) {
        var targetIndex = 0;
        for (var i = 0; i < questionArray.length; i++) {
            if (questionArray[i] == qid) {
                targetIndex = i;
                break;
            }
        }
        __offsetQuestion(targetIndex - currentQuestionIndex);
    }
    window.__offsetQuestion = function (offset) {
        var questionCount = questionArray.length, targetQuesitonIndex = currentQuestionIndex + offset
        if (targetQuesitonIndex < 0 || targetQuesitonIndex >= questionCount) {
            return;
        }
        var lastQuestionId = null, lastGroup = null;
        if (currentQuestionIndex >= 0 && currentQuestionIndex < questionCount) {
            lastQuestionId = questionArray[currentQuestionIndex];
            lastGroup = $('#' + lastQuestionId).parents(PAPER_CLASS.QUESTION_GROUP);
        }

        var targetQuestionId = questionArray[targetQuesitonIndex];
        var targetGroup = $('#' + targetQuestionId).parents(PAPER_CLASS.QUESTION_GROUP);

        if (lastQuestionId == null || lastGroup == null) {
            targetGroup.show();
            $(PAPER_CLASS.GROUP_TITLE, targetGroup).show();
        } else if (lastGroup.attr("id") != targetGroup.attr("id")) {
            $(PAPER_CLASS.GROUP_TITLE, lastGroup).hide();
            lastGroup.hide();
            targetGroup.show();
            $(PAPER_CLASS.GROUP_TITLE, targetGroup).show();
        }
        var lastQuestion = $("#" + lastQuestionId);
        if (lastQuestion.hasClass('ui-question-sub')) {
            lastQuestion.parents(PAPER_CLASS.QUESTION_INDEPENDENCY).hide();
            // 上一题的高度样式恢复
            lastQuestion.parents('.ui-question-independency').children('.ui-question-title:first').css('height', 'auto');
            lastQuestion.css('height', 'auto')
        }
        lastQuestion.hide();

        var targetQuestion = $("#" + targetQuestionId);
        if (targetQuestion.hasClass('ui-question-sub')) {
            var parentQuestion = targetQuestion.parents(PAPER_CLASS.QUESTION_INDEPENDENCY);
            parentQuestion.show();
        }
        targetQuestion.show();

        currentQuestionIndex = targetQuesitonIndex;
        //回调到考试答题卡页面..
        var exam = window.__RTE;
        if (exam) {
            exam.onOffsetQuestion(targetQuestionId);
        }
        setupComplexQuestionHeight(targetQuestionId);
    }

    // ========== 设置复合题的材料和答题内容的高度 ==============//
    function setupComplexQuestionHeight(targetQuestionId) {
        var otherHeight = countOtherTagHeight(targetQuestionId);
        var pageHeight = $(document).height();
        // iframe 的高度
        var winHegith = $(".ui-paper-iframe", window.parent.document).height();
        var targetQuestion = $("#" + targetQuestionId);

        if (targetQuestion.hasClass('ui-question-sub')) {
            var questionTitleTag = targetQuestion.parents('.ui-question-independency').children('.ui-question-title:first');
            if (pageHeight > winHegith) {
                var fitHeight = (winHegith - otherHeight - 70), singleHeight = fitHeight / 2;
                var questionTitleTag = targetQuestion.parents('.ui-question-independency').children('.ui-question-title:first');
                // 如果题干高没有超过高度，材料和小题都设置高度，否则只设置题干的高度
                if (questionTitleTag.height() > singleHeight) {
                    questionTitleTag.css({overflow: 'auto'}).height(singleHeight);
                    targetQuestion.css({overflow: 'auto'}).height(singleHeight);
                } else {
                    fitHeight = fitHeight - questionTitleTag.outerHeight();
                    targetQuestion.css({overflow: 'auto'}).height(fitHeight);
                }
            }
        }
    }

    function countOtherTagHeight(targetQuestionId) {
        var h1 = $('.ui-paper-title').outerHeight();
        var targetQuestion = $("#" + targetQuestionId);
        var h2 = targetQuestion.parents('.ui-question-group').children('.ui-question-group-title:first').outerHeight();
        return h1 + h2;
    }

    // =============== 上传附件 ================//
    function handleClickAttach(questionId) {
        _upload.showSelectDialog(questionId);
    }

    // ================== 摄像头 ============
    function handleClickTakePicture(editor) {
        var takePicture = findTakePicture(window)
        takePicture.showSnapDialog(function (imageData) {
            if (imageData != '') {
                _uploadBase64(imageData, editor);
            }
        });

        // 找到运行环境中的 TakePicture
        function findTakePicture(p) {
            if (!!p.__takePicture) {
                return p.__takePicture;
            } else if (!!p.parent) {
                return findTakePicture(p.parent);
            }
            return null;
        };
    }

    function handleClickHandDraw(editor, questionId, tid) {
        var __handDraw = FindHandDraw(window);
        __handDraw.showHandDrawDialog(function (imageData) {
            if (imageData != '') {
                _uploadBase64(imageData, editor, function (img) {
                    var callbackImg = $(img).width(150).height(50).css({
                        'display': 'inline-block', 'vertical-align': 'middle'
                    });
                    editor.insertHtml(callbackImg[0].outerHTML);
                });
            }
        });

        function FindHandDraw(p) {
            if (!!p.__handDraw) {
                return p.__handDraw;
            } else if (!!p.parent && p.self != p.parent) {
                return FindHandDraw(p.parent);
            }
            return null;
        };
    }

    let myLayer = parent.layer;
    var _upload = {
        maxCount: 3,// 最多上传附件个数
        maxSize: 1024 * 1024 * 5, // 上传附件大小
        inputTag: null, currentId: null, loadIndex: null, init: function () {
            _upload.inputTag = $('<input type="file" id="uploadinput"></input>');
            var toolsbox = $('<div class="tools-box"></div>').hide().append(_upload.inputTag);
            $(document.body).append(toolsbox);
            _upload.inputTag.on('change', function () {
                _upload.uploadFile();
            });
            $('textarea').after($('<ul style="padding:1px solid #fff" class="ui-file-list-new"></ul>'))
        }, _isPicFile: function (fileName) {
            //return true;
            let FILE_EXT_PATTERN = /.jpg|.png|.gif|.bmp|.jpeg|.webp|.jfif/gi;
            let lastIndex = fileName.lastIndexOf('.');
            if (lastIndex < 0) {
                return false;
            } else {
                let extName = fileName.substring(lastIndex);
                if (extName.match(FILE_EXT_PATTERN)) {
                    return true;
                }
            }
            return false;
        }, hasUploadFile: function (question) {
            var fileNumber = $('li', $('.ui-file-list-new', question)).length;
            return fileNumber > 0;
        }, showSelectDialog: function (questionId) {
            _upload.currentId = questionId;
            var len = $('li', $('#' + questionId)).length
            if (len >= _upload.maxCount) {
                parent.layer.msg('最多只能上传 ' + _upload.maxCount + ' 个文件');
                return;
            }
            _upload.inputTag.trigger('click');
        }, _createImageElement: function (qNumberId, fileId, fileName) {
            var exam = window.__RTE;
            var query = $.param({__id: fileId, __name: fileName, __userExamId: exam.userExamId});
            var url = '/exam/student/exam/question/attaches/upload/file/' + qNumberId + '/filePath?inline&' + query;
            if(fileId.indexOf("https")>-1){
            	url = fileId;
            }
            var image = $('<img>').data('url', url);
            var isPicFile = _upload._isPicFile(fileName);
            if (isPicFile) {
                var current = 0;
                image.attr('src', url).on('click', function () {
                    /* exam.previewImage(this);*/
                    current = (current + 90) % 360;
                    this.style.transform = 'rotate(' + current + 'deg)';
                }).attr('title', '预览');
            } else {
                image.attr('src', '/exam/statics/images/document.png').on('click', function () {
                    var form = $('<form style="display:hidden;" target="_blank" action="' + url + '" method="get"></form>');
                    form.append('<input type="hidden" name="__id" value="' + fileId + '"/>');
                    form.append('<input type="hidden" name="__down" value="1"/>');
                    form.append('<input type="hidden" name="__name" value="' + fileName + '"/>');
                    $(document.body).append(form);
                    form.get(0).submit();
                    setTimeout(function () {
                        form.remove();
                    }, 1000);
                }).attr('title', '下载');
            }
            return image;
        }, uploadFile: function () {
            var inputTag = this.inputTag;
            var file = inputTag.prop('files')[0];
            //如果是可以上传附件则不判断文件大小和文件类型
            if (!SUBJ_ANSWER_UPDATE_TYPE.other) {
                if ((file.size > _upload.maxSize)) {
                    var size = _upload.maxSize / 1024 / 1024 + " M";
                    myLayer.msg('上传文件不能超过 ' + size);
                    return;
                }
                if (!_upload._isPicFile(file.name)) {
                    myLayer.msg('只能上传图片文件，如 png, jpg 等');
                    return;
                }
            }
            _upload.loadIndex = parent.layer.msg('正在上传...', {time: 5000, icon: 16, shade: 0.01});
            var exam = window.__RTE;
	   		var ueId = exam.userExamId;
	        formData = new FormData();
	        formData.append('file', file);
	        formData.append('examId', ueId.substr(0,ueId.indexOf("_")));
	        formData.append('userExamId', ueId);
            __doOssUpload(formData, file.name, function (data) {
                _upload._attachFile(_upload.currentId, data.tmpFileName, file.name, true);
                var qt = $('.ui-question-textarea', $('#' + _upload.currentId));
                qt.trigger('change');
                _upload.questionScrollToBottom(_upload.currentId);
            })
            inputTag.val('');
        }, questionScrollToBottom: function (questionId) {
            // 把 question 滚动到底部，
            var question = $('#' + questionId), scrollHeight = question.prop('scrollHeight'),
                height = question.height();
            var moveHeight = scrollHeight - height;
            console.log('move======', moveHeight);
            question.animate({scrollTop: moveHeight}, 800);
            // 把 document 滚动到底部
            var file = $('.ui-file-list-new', question);
            console.log('movefile.offset().top======', file.offset().top);
            $(document.body).animate({scrollTop: file.offset().top}, 800);
        }, showAttachFiles: function (datas, showClose) {
            for (qid in datas) {
                //var qNubmerId = qid.substring(2);
                var files = datas[qid];
                if (files) {
                    var file = files.split(',');
                    for (i in file) {
                        var temp = file[i];
                        if(temp.indexOf("https")>-1){
                        	var fname = temp.substr(temp.lastIndexOf("/")+1);
                        	_upload._attachFile(qid, temp, fname, showClose);
                        }else{
	                        var uploadFile = temp.split('/');
	                        if (temp) if (uploadFile.length < 2) {
	                            _upload._attachFile(qid, uploadFile[0], uploadFile[0], showClose);
	                        } else {
	                            _upload._attachFile(qid, uploadFile[0], uploadFile[1], showClose);
	                        }
                        }
                    }
                }
            }
        }, _attachFile: function (qid, fileId, fileName, showClose) {
            var exam = window.__RTE;
            var qNumberId = qid.replace('q_', '');
            var question = $('#' + qid);
            //var query = $.param({ __id: fileId, __name: fileName,__userExamId: exam.userExamId });
            var li = $('<li><input type="hidden" name="filePath" value="' + fileId + '"/></li>');
            //li.append('<input type="hidden" name="filePath" value="' + fileId + '/' + fileName + '"/>')
            li.append(this._createImageElement(qNumberId, fileId, fileName));
            $('ul', question).append(li);
            if (showClose) {
                var close = $('<span title="删除附件" class="close-button close"></span>').on('click', function () {
                    var closeBtn = $(this);
                    myLayer.confirm('确认删除"' + fileName + '"', {
                        btn: ['确认', '取消'] //按钮
                    }, function () {
                        closeBtn.parent().remove();
                        var qt = $('.ui-question-textarea', question);
                        qt.trigger('change');
                        myLayer.closeAll();
                    }, function () {
                        myLayer.closeAll();
                    });
                })
                li.append(close);
            }
        }
    }


    // =========================== 手写板 ==========================
    var enableHandle = true, enableHandleInterval = 3000;

    function handleClickDrawPainter(editor, questionId, tid) {
        if (!enableHandle) return;
        //webkite的手写板，或是浏览器自动的手写板;
        try {
            writingBoard.Open(questionId, tid);
        } catch (e) {
            try {
                clickToolbar(editor);
            } catch (e) {
                console.log(e);
                alert('需要专用手写板支持');
            }
        }
        ;enableHandle = false;
        setTimeout(function () {
            enableHandle = true;
        }, enableHandleInterval);
    }

    var _currentEditor = null;
    window.__webkitCallback_insertHtml = function (questionId, textareaId, tempName, fileName) {
        if (tempName && fileName) {
            var baseUrl = '/exam/student/exam/question/attaches';
            var param = {
                __id: tempName, __name: function () {
                    return encodeURI('draw_' + fileName);
                }
            }, query = $.param(param);
            var img = '<p><img alt="' + fileName + '" src="' + baseUrl + '/upload/file/-9/filePath?' + query + '"/></p>';
            _currentEditor.insertHtml(img);
        }
    }
    window.__webkitCallback_inserBase64Img = function (questionId, base64Content, fileName) {
        //data:image/png;base64,
        var img = '<img alt="' + fileName + '" src="' + base64Content + '"/>';
        _currentEditor.insertHtml(img);
    }
    window.clickToolbar = function (editor) {
        var kpainter = FindPainter(window);
        kpainter.clear();
        kpainter.connect();
        kpainter.autoSave();
        __RTE.ShowPainter({
            yes: function () {
                _uploadBase64(kpainter.getImageDataUrl(), __RTE.getEditor());
                kpainter.clearInterval();
                kpainter.save();
                __RTE.closePainter();
                kpainter.disconnect();
            }, reset: function () {
                if (confirm('确定清空手绘板？')) {
                    kpainter.clear();
                }
                kpainter.clearInterval();
            }, cancel: function () {
                kpainter.clearInterval();
                kpainter.disconnect();
            }, editor: editor
        });

        // 自动保存存
        function FindPainter(p) {
            console.log(p.parent);
            console.log(!!p.parent);
            if (!!p.__board) {
                return p.__board;
            } else if (!!p.parent && p.self != p.parent) {
                return FindPainter(p.parent);
            }
            return null;
        };

    }

    //=================   上传b base64 图片和回写 editor ===================

    function _uploadBase64(base64Data, editor, callback) {
        var baseUrl = '/exam/student/exam/question/attaches';
        var $Blob = getBlobBydataURI(base64Data, 'image/png');
        var formData = new FormData(), fileName = "draw_" + Date.parse(new Date()) + ".png";
        formData.append("file", $Blob, fileName);
        __doAjaxUpload(formData, fileName, function (json) {
            var tempName = json.tmpFileName, param = {
                __id: tempName, __name: function () {
                    return encodeURI(fileName);
                }
            }, query = $.param(param);
            var img = '<img alt="' + fileName + '" src="' + baseUrl + '/upload/file/-9/filePath?' + query + '"/>';
            if (callback) {
                callback(img);
            } else {
                editor.insertHtml(img);
            }
        });

        function getBlobBydataURI(dataURI, type) {
            var binary = atob(dataURI.split(',')[1]);
            var array = [];
            for (var i = 0; i < binary.length; i++) {
                array.push(binary.charCodeAt(i));
            }
            return new Blob([new Uint8Array(array)], {type: type});
        }
    }
    
    function __doOssUpload(formData, fileName, callback) {
        var baseUrl = '/exam/oss/attaches';
        $.ajax({
            url: baseUrl + '/upload',
            type: 'POST',
            data: formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            dataType: 'text',
            success: function (data) {
                var json = $.parseJSON(data);
                if (json && json.success && json.tmpFileName) {
                    callback(json);
                } else {
                    alert('上传出错，请与系统管理员联系..');
                }
                parent.layer.closeAll();
            },
            error: function (returndata) {
                alert("上传出错，请与系统管理员联系.." + returndata);
                parent.layer.closeAll();
            },
            beforeSend: function (xhr) {
                xhr.setRequestHeader("X-File-Name", encodeURIComponent(fileName));
            }
        });
    }

    function __doAjaxUpload(formData, fileName, callback) {
        var baseUrl = '/exam/student/exam/question/attaches';
        $.ajax({
            url: baseUrl + '/upload/filePath/form',
            type: 'POST',
            data: formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            dataType: 'text',
            success: function (data) {
                var json = $.parseJSON(data);
                if (json && json.success && json.tmpFileName) {
                    callback(json);
                } else {
                    alert('上传出错，请与系统管理员联系..');
                }
                parent.layer.closeAll();
            },
            error: function (returndata) {
                alert("上传出错，请与系统管理员联系.." + returndata);
                parent.layer.closeAll();
            },
            beforeSend: function (xhr) {
                xhr.setRequestHeader("X-File-Name", encodeURIComponent(fileName));
            }
        });
    }


    /**
     * 生成随机数的类，参数为随机数的种子，如果种子相同，则生成的随机数序列一样。
     *
     * @param {String} seed 字符串的随机数种子
     */
    function Random(seed) {
        this.seed = this.hashCode(seed);
    }

    Random.prototype.hashCode = function (str) {
        str = str + '';
        var hash = 0;
        if (str.length == 0) return hash;
        for (i = 0; i < str.length; i++) {
            char = str.charCodeAt(i);
            hash = ((hash << 5) - hash) + char;
            hash = hash & hash; // Convert to 32bit integer
        }
        return hash;
    }
    Random.prototype.rand = function (max) {
        this.seed = (this.seed * 9301 + 49297) % 233280;
        var t = this.seed / (233280.0);
        var tt = Math.abs(Math.ceil(t * max));
        return tt == max ? max - 1 : tt;
    }

    window.showStudentExtraInfo = function (info) {
        var defaultPhotUrl = "${staticResPath}/images/dk_photo.png";
        var examPhoto = $('#examPhoto');
        if (info.url) {
            var imageGetUrl = info.url + '?examCode=' + info.examCode + '&unit=' + info.unit + '&siteCode=' + info.siteCode + '&roomCode=' + info.roomCode + '&idCardNo=' + info.idCardNo;
            $.get(imageGetUrl, function (result) {
                if (result.success && result.data) {
                    examPhoto.attr("src", result.data);
                } else {
                    examPhoto.attr('src', defaultPhotUrl);
                }
            });
        } else {
            examPhoto.attr('src', defaultPhotUrl);
        }
    }

})(jQuery);
